package com.huatai.vba.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.huatai.vba.common.exception.BusinessException;
import com.huatai.vba.dal.dao.VbaFileActionDAO;
import com.huatai.vba.dal.dao.VbaFileActionRecordDAO;
import com.huatai.vba.dal.model.VbaFileAction;
import com.huatai.vba.dal.model.VbaFileActionRecord;
import com.huatai.vba.execute.action.ActionExecutor;
import com.huatai.vba.service.VbaFileActionService;

@Service
public class VbaFileActionServiceImpl implements VbaFileActionService, ApplicationContextAware {

	protected static final Logger logger = LoggerFactory.getLogger(VbaFileActionServiceImpl.class);

	@Autowired
	private VbaFileActionDAO vbaFileActionDAO;

	@Autowired
	private VbaFileActionRecordDAO vbaFileActionRecordDAO;

	private ApplicationContext applicationContext;

	@Override
	public VbaFileAction queryVbaFileAction(String actionId) throws BusinessException {
		return vbaFileActionDAO.queryById(actionId);
	}

	@Override
	public List<VbaFileAction> queryVbaFileAction(VbaFileAction vbaFileAction) throws BusinessException {
		if (vbaFileAction == null)
			vbaFileAction = new VbaFileAction();
		return vbaFileActionDAO.queryByModel(vbaFileAction);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public boolean executeAction(String actionId, String actionExecutor) {
		VbaFileAction action = vbaFileActionDAO.queryById(actionId);

		Long startTime = System.currentTimeMillis();
		VbaFileActionRecord record = new VbaFileActionRecord();
		record.setOccurDate(new Date());
		record.setActionId(actionId);
		record.setActionExecutor(actionExecutor);
		try {
			logger.info("bean对象：" + action.getActionTemplateName());
			ActionExecutor executor = (ActionExecutor) applicationContext.getBean(action.getActionTemplateName());
			if (executor == null) {
				throw new BusinessException("bean对象：" + action.getActionTemplateName() + "未找到");
			}
			executor.execute(action);
			record.setStatus("1");
			record.setMsg("执行成功");
		} catch (Exception ex) {
			record.setMsg(ex.getMessage());
			record.setStatus("0");
		}
		Long endTime = System.currentTimeMillis();
		record.setCostTime((endTime - startTime) / 1000);
		vbaFileActionRecordDAO.insert(record);
		return record.getStatus().equals("1");
	}

}
